from typing import Any, List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from datetime import datetime

from app.api import deps
from app.schemas import hotel_order as schemas
from app.database.models.erp import HotelOrder, CustomerProfile, PackageOrder, HotelOrderPassenger
from app.database.models.base import User

router = APIRouter()

@router.get("/", response_model=List[schemas.HotelOrder])
def list_hotel_orders(
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_agent_user),
    skip: int = 0,
    limit: int = 100
):
    """获取酒店订单列表"""
    orders = db.query(HotelOrder)\
        .filter(HotelOrder.work_area_id == current_user.workarea_id)\
        .offset(skip)\
        .limit(limit)\
        .all()
    return orders

@router.post("/", response_model=schemas.HotelOrder)
def create_hotel_order(
    *,
    db: Session = Depends(deps.get_db),
    order_in: schemas.HotelOrderCreate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """创建新的酒店订单"""
    try:
        # 使用当前用户的工作区ID
        order_data = order_in.dict()
        order_data["work_area_id"] = current_user.workarea_id

        # 设置默认值
        if not order_data.get("package_order_id") or order_data["package_order_id"] <= 0:
            order_data["package_order_id"] = -1
            order_data["package_order_title"] = None
        else:
            # 如果关联了打包订单，查询订单标题
            package_order = db.query(PackageOrder).filter(
                PackageOrder.ID == order_data["package_order_id"]
            ).first()
            if package_order:
                order_data["package_order_title"] = package_order.title

        order = HotelOrder(**order_data)
        db.add(order)
        db.commit()
        db.refresh(order)
        return order
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/{order_id}", response_model=schemas.HotelOrder)
def get_hotel_order(
    order_id: int,
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取特定酒店订单详情"""
    try:
        order = db.query(HotelOrder).filter(HotelOrder.ID == order_id).first()
        if not order:
            raise HTTPException(status_code=404, detail="Hotel order not found")

        # 检查权限
        if current_user.role != "admin" and order.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        return order
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.put("/{order_id}", response_model=schemas.HotelOrder)
def update_hotel_order(
    *,
    db: Session = Depends(deps.get_db),
    order_id: int,
    order_in: schemas.HotelOrderUpdate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """更新酒店订单信息"""
    try:
        order = db.query(HotelOrder).filter(HotelOrder.ID == order_id).first()
        if not order:
            raise HTTPException(status_code=404, detail="Hotel order not found")

        # 检查权限
        if current_user.role != "admin" and order.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 更新订单信息
        update_data = order_in.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(order, field, value)

        db.add(order)
        db.commit()
        db.refresh(order)
        return order
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/{order_id}")
def delete_hotel_order(
    *,
    db: Session = Depends(deps.get_db),
    order_id: int,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """删除酒店订单"""
    try:
        order = db.query(HotelOrder).filter(HotelOrder.ID == order_id).first()
        if not order:
            raise HTTPException(status_code=404, detail="Hotel order not found")

        if current_user.role != "admin" and order.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        db.delete(order)
        db.commit()
        return {"ok": True}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e)) 